/**
 * 
 */
package org.compiere.report;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Properties;
import java.util.logging.Level;

import org.adempiere.exceptions.AdempiereException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.compiere.model.I_BPM_Project;
import org.compiere.model.I_BPM_VersionBudget;
import org.compiere.model.MAttachmentEntry;
import org.compiere.model.MBPMForm;
import org.compiere.model.MBPMFormColumn;
import org.compiere.model.MBPMFormLine;
import org.compiere.model.MBPMFormValues;
import org.compiere.model.MOrg;
import org.compiere.process.ProcessInfo;
import org.compiere.process.ProcessInfoParameter;
import org.compiere.process.SvrProcess;
import org.compiere.util.Env;
import org.compiere.util.Msg;

import extend.org.compiere.utils.Util;

/**
 * @author Aslanbek
 */
public class BPM_Form11_12 extends SvrProcess {
	/** Current context */
	private Properties m_ctx;
	private ProcessInfo pi;
	int p_BPM_Form_ID = 0;
	int p_BPM_Project_ID = 0;
	int p_AD_Org_ID = 0;
	int p_BPM_VersionBudget_ID = 0;
	int p_C_Year_ID = 0;
	/** */
	String ResultPath;
	
	protected void prepare() {
		log.info("Prepare methos of BPM_Form11_12 report");
		m_ctx = Env.getCtx();
		pi = getProcessInfo();
		ProcessInfoParameter[] para = getParameter();
		for (int i = 0; i < para.length; i++) {
			String name = para[i].getParameterName();
			if (para[i].getParameter() == null)
				;
			else if (name.equals(I_BPM_VersionBudget.COLUMNNAME_BPM_VersionBudget_ID))
				p_BPM_VersionBudget_ID = para[i].getParameterAsInt();
			else if (name.equals(I_BPM_Project.COLUMNNAME_BPM_Project_ID))
				p_BPM_Project_ID = para[i].getParameterAsInt();
			else if (name.equals("BPM_Form_ID")) 
				p_BPM_Form_ID  = para[i].getParameterAsInt();
			else if (name.equals("AD_Org_ID"))
				p_AD_Org_ID = para[i].getParameterAsInt();
			else if (name.equals("C_Year_ID")) 
				p_C_Year_ID  = para[i].getParameterAsInt();
			else
				log.log(Level.SEVERE, "Unknown Parameter: " + name);
		}
	}

	protected String doIt() throws Exception {
		
		MBPMForm form = null;
		
		if(p_BPM_Form_ID>0)
			 form = new MBPMForm(m_ctx, p_BPM_Form_ID, get_TrxName());
		else 
			return "Бюджетная форма не указана";
		
		//File path
		ResultPath = Util.getResultPath(form.getName(), (new String(form.getName()).length())+1);
		MAttachmentEntry entry = Util.getAttachment(pi, m_ctx, ResultPath);
		if (entry == null)
			throw new AdempiereException(Msg.translate(m_ctx,"NotFoundTemplate"));

		XSSFWorkbook wb = new XSSFWorkbook(entry.getInputStream());
		XSSFSheet sheet = wb.getSheetAt(0);
		Row R = null;
		
		int colNo = 0;
		int rowNo = 5;
		//Title
		R = sheet.createRow(1);
		R.createCell(0).setCellValue(form.getName().substring(8, form.getName().length()));
		R.getCell(0).setCellStyle(sheet.getRow(0).getCell(2).getCellStyle());
		sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 4));
		//Org Name
		R = sheet.createRow(3);
		R.createCell(0).setCellValue("Наименование организации: "+new MOrg(m_ctx, p_AD_Org_ID, get_TrxName()).getDescription());
		R.getCell(0).setCellStyle(sheet.getRow(0).getCell(3).getCellStyle());
		sheet.addMergedRegion(new CellRangeAddress(3, 3, 0, 4));
		
		R = sheet.createRow(rowNo);
		MBPMFormColumn[] columns = null;
		
		if(p_C_Year_ID>0)
			columns = MBPMFormColumn.getLineFormCode(m_ctx, form.getBPM_FormCode_ID(), p_C_Year_ID, get_TrxName());
		else
			columns = MBPMFormColumn.getLineFormCode(m_ctx, form.getBPM_FormCode_ID(), get_TrxName());
		
		for(MBPMFormColumn column : columns)
		{
			R.createCell(colNo).setCellValue(column.getName());
			R.getCell(colNo).setCellStyle(sheet.getRow(0).getCell(0).getCellStyle());
			//костыль
			if(column.getBPM_FormColumn_ID()==1000223 || column.getBPM_FormColumn_ID()==1001715) // Единца измерения формы 11 и 12
				R.getSheet().setColumnWidth(colNo, 2500);

			if((column.getBPM_FormColumn_ID() >= 1001717 && column.getBPM_FormColumn_ID() <= 1001726) //показателей по годам,Факт/План форма 12
					||(column.getBPM_FormColumn_ID() >= 1000225 && column.getBPM_FormColumn_ID() <= 1000229)//показателей по годам,Факт1/План форма 11
					||(column.getBPM_FormColumn_ID() >= 1001765 && column.getBPM_FormColumn_ID() <= 1001769))//показателей по годам,Факт/План1 форма 11

					R.getSheet().setColumnWidth(colNo, 3000);
			colNo++;			
		}
		
		rowNo++;
		
		for(MBPMFormLine formLine : form.getLines(true))
		{
			R = sheet.createRow(rowNo);
			colNo = 0;
			for(MBPMFormColumn column : columns)
			{
			
				String str = MBPMFormValues.getCellValue(formLine.getBPM_FormLine_ID(), column.getBPM_FormColumn_ID(), p_BPM_Project_ID, p_AD_Org_ID, getAD_Client_ID());
				R.createCell(colNo).setCellValue(str);
				R.getCell(colNo).setCellStyle(sheet.getRow(0).getCell(1).getCellStyle());
				colNo++;			
			}
			
			rowNo++;
		}
		R = sheet.getRow(0);
		R.getCell(0).setCellValue("");
		R.getCell(0).setCellStyle(R.getCell(3).getCellStyle());
		R.getCell(1).setCellValue("");
		R.getCell(1).setCellStyle(R.getCell(3).getCellStyle());
		R.getCell(2).setCellValue("");
		R.getCell(2).setCellStyle(R.getCell(3).getCellStyle());
		R.getCell(3).setCellValue("");
		// Write the output to a file
		FileOutputStream fileOut = new FileOutputStream(ResultPath);
		wb.write(fileOut);
		fileOut.close();
		// Open the file with the application associated
		Util.launchFile(new File(ResultPath));	
		
		return Msg.translate(m_ctx, "Success");
	}
}
